package com.atguigu.Func;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.Util.JdbcUtil;
import com.atguigu.bean.TableProcess;
import org.apache.flink.api.common.state.BroadcastState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.state.ReadOnlyBroadcastState;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.co.BroadcastProcessFunction;
import org.apache.flink.util.Collector;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.HashMap;
import java.util.List;

/**
 * @author hjy
 * @create 2023/3/13 16:21
 */
public class DwdTableProcessFunction extends BroadcastProcessFunction<JSONObject,String,JSONObject> {
        private MapStateDescriptor<String, TableProcess> mapStateDescriptor;
        private HashMap<String, TableProcess> hashMap;
    public DwdTableProcessFunction(MapStateDescriptor<String, TableProcess> mapStateDescriptor) {
        this.mapStateDescriptor = mapStateDescriptor;
    }

    @Override
    public void open(Configuration parameters) throws Exception {
        hashMap=new HashMap<>();
        Connection conn = DriverManager.getConnection("jdbc:mysql://hadoop102:3306/gmall_config?" +
                "user=root&password=123456&useUnicode=true&" +
                "characterEncoding=utf8&serverTimeZone=Asia/Shanghai&useSSL=false");
        List<TableProcess> tableProcessList = JdbcUtil.getJdbcUtil(conn, "select * from table_process where sink_type='dwd'", TableProcess.class, true);
        for (TableProcess tableProcess : tableProcessList) {
            String key = tableProcess.getSourceTable() + "-" + tableProcess.getSourceType();
            hashMap.put(key,tableProcess);
        }
    }

    //value
    // {"before":null,"after":{"source_table":"base_category3","sink_table":"dim_base_category3","sink_columns":"id,name,category2_id","sink_pk":"id","sink_extend":null},"source":{"version":"1.5.4.Final","connector":"mysql","name":"mysql_binlog_source","ts_ms":1669162876406,"snapshot":"false","db":"gmall-220623-config","sequence":null,"table":"table_process","server_id":0,"gtid":null,"file":"","pos":0,"row":0,"thread":null,"query":null},"op":"r","ts_ms":1669162876406,"transaction":null}
    @Override
    public void processBroadcastElement(String value, Context ctx, Collector<JSONObject> out) throws Exception {
        //拿到状态的数据
        BroadcastState<String, TableProcess> broadcastState = ctx.getBroadcastState(mapStateDescriptor);
        JSONObject jsonObject = JSONObject.parseObject(value);
        String op = jsonObject.getString("op");
        if ("d".equals(op)){
            TableProcess before = jsonObject.getObject("before", TableProcess.class);
            if ("dwd".equals(before.getSinkType())){
                String key = before.getSourceTable() + "-" + before.getSourceType();
                broadcastState.remove(key);
                hashMap.remove(key);
            }
        }else {
            TableProcess after = jsonObject.getObject("after", TableProcess.class);
            if ("dwd".equals(after.getSinkType())){
                String key = after.getSourceTable() + "-" + after.getSourceType();
                broadcastState.put(key,after);
            }
        }
    }

    //{"database":"gmall-220623-flink","table":"comment_info","type":"insert","ts":1669162958,"xid":1111,"xoffset":13941,"data":{"id":1595211185799847960,"user_id":119,"nick_name":null,"head_img":null,"sku_id":31,"spu_id":10,"order_id":987,"appraise":"1204","comment_txt":"评论内容：48384811984748167197482849234338563286217912223261","create_time":"2022-08-02 08:22:38","operate_time":null}}
    @Override
    public void processElement(JSONObject value, ReadOnlyContext ctx, Collector<JSONObject> out) throws Exception {
        ReadOnlyBroadcastState<String, TableProcess> broadcastState = ctx.getBroadcastState(mapStateDescriptor);
        String key = value.getString("table") + "-" + value.getString("type");
        TableProcess tableProcess = broadcastState.get(key);
        TableProcess mapTableProcess = hashMap.get(key);
        if (tableProcess!=null||mapTableProcess!=null){
            if (tableProcess==null){
                tableProcess=mapTableProcess;
            }
            value.put("sink_table",tableProcess.getSinkTable());
            out.collect(value);
        }
    }


}
